include(FetchContent)

set(VERILATOR_NAME verilator)
#set(VERILATOR_INCLUDE_DIR ${VERILATOR_ROOT}/include)
#set(VERILATOR_URL https://mirror.msys2.org/mingw/mingw64/mingw-w64-x86_64-verilator-4.218-2-any.pkg.tar.zst)
set(VERILATOR_URL https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/mingw64/mingw-w64-x86_64-verilator-4.218-2-any.pkg.tar.zst)

set(VERILATOR_SOURCE_ROOT ${PROJECT_SOURCE_DIR}/download/${VERILATOR_NAME})

include(FetchContent)
FetchContent_Declare(${VERILATOR_NAME}
        URL ${VERILATOR_URL}
        SOURCE_DIR ${VERILATOR_SOURCE_ROOT}
        URL_HASH SHA1=19125525397C3EB766AFFF2563727354B2D8585E)
FetchContent_GetProperties(${VERILATOR_NAME})
if (NOT ${VERILATOR_NAME}_POPULATED AND NOT EXISTS ${VERILATOR_SOURCE_ROOT})
    message(STATUS "Downloading ${VERILATOR_NAME} from ${VERILATOR_URL}")
    FetchContent_Populate(${VERILATOR_NAME})
endif ()

set(VERILATOR_ROOT ${VERILATOR_SOURCE_ROOT}/mingw64)

message(STATUS "VERILATOR_ROOT = ${VERILATOR_ROOT}")

# Copy includes
file(COPY ${VERILATOR_ROOT}/share/verilator/include DESTINATION ${VERILATOR_ROOT})
file(COPY ${VERILATOR_ROOT}/bin DESTINATION ${VERILATOR_ROOT}/share/verilator)

find_package(verilator HINTS $ENV{VERILATOR_ROOT} ${VERILATOR_ROOT})
if (NOT verilator_FOUND)
    message(FATAL_ERROR "Verilator was not found. Either install it, or set the VERILATOR_ROOT environment variable.")
endif ()
#add_library(${VERILATOR_NAME} SHARED IMPORTED)

if (USE_SYSTEMC)
    # Not tested now
    if (MINGW)
        set(MSVC true)       # SystemC tries to assemble quick threads if this isn't added
    endif (MINGW)

    set(SYSTEMC_PREFIX ${PROJECT_BINARY_DIR}/systemc)
    set(SYSTEMC_INCLUDE_DIR ${SYSTEMC_PREFIX}/src/systemc/src)
    ExternalProject_Add(systemc
            DOWNLOAD_DIR ${X_ROOT}/download
            DOWNLOAD_NAME systemc-src.zip
            PREFIX ${SYSTEMC_PREFIX}
            URL https://github.com/accellera-official/systemc/archive/4a44d3619eca48a7a99122ae8c0fe3baf101d2e5.zip
            URL_HASH SHA1=B8CABDF64B61630B3DBA1E292F548CDE906FEC90
            CMAKE_ARGS -DCMAKE_CXX_STANDARD=14 -DCMAKE_INSTALL_PREFIX=${SYSTEMC_PREFIX}/install
            )
    include_directories(${SYSTEMC_PREFIX}/install/include)
    link_libraries(${SYSTEMC_PREFIX}/install/lib/libsystemc.a)
endif ()